package org.apache.servicecomb.samples.practise.houserush.realestate.api;

import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.Building;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.House;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.Realestate;
import org.apache.servicecomb.samples.practise.houserush.realestate.service.RealestateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.Path;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@RestSchema(schemaId = "realestateApiTest")
@RequestMapping("/")
public class RealestateApiRestImpl implements RealestateApi {

    @Autowired
    private RealestateService realestateService;


    @GetMapping("testProvider")
    public Date testProvider() {
        return new Date();
    }


    @PostMapping("realestates")
    public Realestate createRealesate(@RequestBody Realestate realestate) {
        return realestateService.createRealesate(realestate);
    }


    @GetMapping("realestates/{id}")
    public Realestate findRealestate(@PathVariable("id") Integer id) {
        return realestateService.findRealestate(id);
    }

    @GetMapping("realestates/findAll")
    @Override
    public List<Realestate> indexRealestates() {
        return realestateService.indexRealestates();
    }

    @Override
    @PutMapping("realestates/{id}")
    public Realestate updateRealestate(@PathVariable int id,@RequestBody Realestate realestate) {
        realestate.setId(id);

        return realestateService.updateRealestate(realestate);
    }

    @DeleteMapping("realestates/{id}")
    @Override
    public void removeRealestate(@PathVariable int id) {
        realestateService.removeRealestate(id);
    }

    @Override
    @GetMapping("realestates/findTreeRealestate/{id}")
    public Realestate findByRealestateId(@PathVariable("id") Integer id) {
        Realestate realestate = realestateService.findRealestate(id);
        List<Building> buildings = realestate.getBuildings();
        for (Building building : buildings) {
            List<House> houses = building.getHouses();
            Iterator<House> iterator = houses.iterator();
            while(iterator.hasNext()) {
                House house = iterator.next();
                if("locking".equals(house.getState())) {
                    iterator.remove();
                }
            }
        }
        return realestate;
    }


}
